<?php

/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2020/5/26
 * Time: 16:09
 */
class ctrl_wish_product extends L {

    /**
     * 描述 : 整理导入的文件
     * 作者 : Zoro.Zhu
     */
    public function index() {
        if(!empty($_POST['fileUrl'])){
            set_time_limit(0);
            ini_set('memory_limit', '4096M');
            L::open('excel');
            $path = ROOT_DIR . '/data' . $_POST['fileUrl'];
            $shipFee = isset($_POST['shipFee']) && $_POST['shipFee'] !== '' ? $_POST['shipFee'] : 2;
            $price = isset($_POST['price']) && $_POST['price'] !== '' ? ($_POST['price'] / 100 + 1) : 1.2;
            $updTitle = !empty($_POST['updTitle']) ? true : false;
            $getUrlInfo = !empty($_POST['getUrlInfo']) ? true : false;
            $data = self::excel2arr($path);
            self::exportData($data, $shipFee, $price, $updTitle, $getUrlInfo);
        }else{
            $this->view->headTitle = '整理店小秘刊登数据';
            $this->display('/html/wish/exportProduct.html');
        }
    }

    public function getUrlAll() {
        set_time_limit(0);
        $y = true;
        for ($page = 1; $y == true; $page ++){
            $res = serv_rapi_publish::search(array('platformId' => 1,                                  //平台
                'siteCode' => ['US'],                               //站点
                'size' => 500,                                      //查询多少个
                'page' => $page,                                    //第几页
                'goodsCategoryId1' => ['293'],                    //类目 //11700 家居 //14339 工艺品 // 293 家用电子产品 // 888 运动产品 //1201 宠物产品 6000 机动车
                'itemQuantitySoldFrom' => 1,                       //已售出数量
                'shippingCostTo' => 0,                              //运费
//                'startTimeFrom' => '2020-07-15',                         //上架时间
                'sort' => 'quantitySold ASC',                      //售出数量降序
            ));
            if(empty($res['data'])){
                $y = false;
            }
            foreach ($res['data'] as $row) {
                echo 'https://www.ebay.com/itm/' . $row['itemId'] . "\t" . $row['mainSku'] . '<br>'; //US // eBayMotors
//                echo 'https://www.ebay.co.uk/itm/' . $row['itemId'] . '<br>'; //UK
//                            echo 'https://www.ebay.ca/itm/' . $row['itemId'] . '<br>'; //Canada
            }
        }
    }

    public function downloadBatch(){
        $tempList = scandir(ROOT_DIR . "/data/upload/chanp/");
        $list = [];
        foreach ($tempList as $k => $v) {
            if ($v == '.' || $v == '..') {
                continue;
            }
            $list[] = $v;
        }
        echo "<script language=javascript>
        var urls=new Array('" . join("','", $list) . "');
        for (i in urls) document.write('<a id=\"d'+i+'\" href=\"http://127.0.0.1/vs/?c=ctrl_wish_product&a=exportEcxle&fileName='+urls[i]+'\" target=_blank>x</a>');
        for (i in urls) document.getElementById('d'+i).click();
        </script>";
    }

    /**
     * 描述 : 整理导出的文件
     * 作者 : Zoro.Zhu
     */
    public function exportEcxle() {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        L::open('excel');
        $path = ROOT_DIR . "/data/upload/chanp/" . $_GET['fileName'];
        $data = self::excel2arr($path);
        self::exportData($data);
    }

    /**
     * 描述 : 整理表格数据
     * 作者 : Zoro.Zhu
     */
    public static function exportData($data,$shippingFee = 4, $price = 1.2,$updTitle = false,$getUrlInfo = false){
        $objPHPExcel = new PHPExcel();
        $imgUrl = $newTitle = $oldTitle = $id = '';
        foreach ($data as $h => $ros){
            $purchaseUrl = '';
            if(!empty($ros[11]) && $getUrlInfo){
                $productInfo = self::getPurchaseUrl(trim($ros[11]));
                if(!empty($productInfo)){
                    $purchaseUrl = $productInfo['url'];
                }
            }
            $maxPrice = 0;
            if(!empty($productInfo['data']['skuAttr'])){
                foreach ($productInfo['data']['skuAttr'] as $p) {
                    $p['shopPrice'] > $maxPrice && $maxPrice = $p['shopPrice'];
                }
            }
            foreach($ros as $l => $r){
                $r = trim($r);
                $lName = !empty($l) ? PHPExcel_Cell::stringFromColumnIndex($l) : 'A';
                //处理第一行标题
                if($h === 1){
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $r);
                }else{
//                    if(empty($purchaseUrl)){
//                        break;
//                    }
                    if($maxPrice > 1 && $maxPrice < 10000){
                        $totalPrice = trim($maxPrice) * $price * 7;
                    } elseif ($ros[12] > 10000 || $ros[12] == $ros[13]){
                        $totalPrice = trim($ros[13]) * $price;
                    } else {
                        $totalPrice = trim($ros[12]) * $price * 7;
                    }
                    $totalPrice += $shippingFee * 7;
                    //处理内容
                    if($l == 2) {
                        //判断是不是同一个产品，根据标题是否一直判断
                        if($oldTitle != $r){
                            $id = of_base_com_str::uniqid('Z',3);
                            $fee = round($totalPrice * 0.2, 2);
                            //更换标题
                            if($updTitle === true){
                                //标题
                                $title = explode(' ', $r);
                                shuffle($title);
                                $newTitle = join(" ", $title);
                                //主图
                                $imgArray = [];
                                !empty(trim($ros[19])) && $imgArray[] = $ros[19];
                                !empty(trim($ros[21])) && $imgArray[] = $ros[21];
                                !empty(trim($ros[22])) && $imgArray[] = $ros[22];
                                !empty(trim($ros[23])) && $imgArray[] = $ros[23];
                                !empty(trim($ros[24])) && $imgArray[] = $ros[24];
                                !empty(trim($ros[25])) && $imgArray[] = $ros[25];
                                !empty(trim($ros[26])) && $imgArray[] = $ros[26];
                                !empty(trim($ros[27])) && $imgArray[] = $ros[27];
                                !empty(trim($ros[28])) && $imgArray[] = $ros[28];
                                !empty(trim($ros[29])) && $imgArray[] = $ros[29];
                                !empty(trim($ros[30])) && $imgArray[] = $ros[30];
                                $imgUrlKey = array_rand($imgArray, 1);
                                $imgUrl = $imgArray[$imgUrlKey];
                                unset($imgArray[$imgUrlKey]);
                                $imgArray = array_values($imgArray);
                            } else {
                                $newTitle = $r;
                                $imgUrl = $ros[19];
                            }
                        }
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $h, $id);
                        //标题
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $newTitle);
                        $oldTitle = $r;
                    }elseif($l == 1){
                        //处理SKU
                        $sku = of_base_com_str::uniqid();
                        !empty(trim($ros[9])) && $sku .= '_' . trim($ros[9]);
                        !empty(trim($ros[10])) && $sku .= '_' . trim($ros[10]);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $sku);
                    }elseif($l == 9 || $l == 10){
                        //处理颜色和尺寸
                        if(!empty(trim($ros[9])) && empty(trim($ros[10]))){
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $h, '');
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K' . $h, trim($ros[9]));
                        }else{
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $h, trim($ros[9]));
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K' . $h, trim($ros[10]));
                        }
                    }elseif($l == 3){
                        $r = trim($r, 'Condition: New: A brand-new, unused, unopened and undamaged item in original retail packaging (where packaging is applicable). If the item comes direct from a manufacturer, it may be delivered in non-retail packaging, such as a plain or unprinted box or plastic bag. See the seller&#39;s listing for full details. See all condition definitions– opens in a new window or tab ... Read moreabout the condition');
                        $r = trim($r, 'Packaging should be the same as what is found in a retail store, unless the item is handmade or was packaged by the manufacturer in non-retail packaging, such as an unprinted box or plastic bag. See the seller&#39;s listing for full details. See all condition definitions- opens in a new window or tab ... Read moreabout the condition');
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $r);
                    }elseif($l == 4){
                        $flag = explode(',', $r);
                        shuffle($flag);
                        foreach ($flag as $k => $f){
                            if($k > 9){
                                unset($flag[$k]);
                            }
                        }
                        $flag = join(',', $flag);
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $flag);
                    }elseif($l == 11){
                        if(!empty($r)){
                            $url = $r . "\n" . join("\n", $purchaseUrl);
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $url);
                        }else{
                            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $r);
                        }
                    }elseif($l == 12){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, round($totalPrice * 0.8 / 7, 2));
                    }elseif($l == 13){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, round($totalPrice * 0.8, 2));
                    }elseif($l == 14){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, round($fee / 7, 2));
                    }elseif($l == 15){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, round($fee, 2));
                    }elseif($l == 16){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, 100);
                    }elseif($l == 19){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $imgUrl);
                    }elseif ($updTitle === true && $l > 20 && $l < 41){
                        $l = $l - 21;
                        $url = !empty($imgArray[$l]) ? $imgArray[$l] : '';
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $url);
                    }else{
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($lName . $h, $r);
                    }
                }
            }
        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="wishOk.xls"');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');      //xls 标准
        $objWriter->save('php://output');                                           //下载
    }

    /**
     * 描述 : 解析excle表格
     * 作者 : Zoro.Zhu
     */
    public static function excel2arr($filePath) {
        if (!file_exists($filePath)) {
            exit("not found $filePath.\n");
        }

        //默认用excel2007读取excel，若格式不对，则用之前的版本进行读取
        $reader = new PHPExcel_Reader_Excel2007();
        if (!$reader->canRead($filePath)) {
            $reader = new PHPExcel_Reader_Excel5();
            if (!$reader->canRead($filePath)) {
                return 'no Excel';
            }
        }
        $PHPExcel = $reader->load($filePath); // 载入excel文件
        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumm = $sheet->getHighestColumn(); // 取得总列数
        $highestColumm = PHPExcel_Cell::columnIndexFromString($highestColumm); //字母列转换为数字列 如:AA变为27

        /** 循环读取每个单元格的数据 */
        for ($row = 1; $row <= $highestRow; $row++) {//行数是以第1行开始
            for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
                $a = $sheet->getCellByColumnAndRow($column, $row)->getValue() . " ";
                $excelarr[$row][] = $a;
            }
        }
        return $excelarr;
    }


    /**
     * 描述 : 获取购买链接
     * 作者 : Zoro.Zhu
     */
    public static function manuUrl($itemId, $type){
        if($type == 'ebay'){
            $res = serv_rapi_publish::getEbayItemInfo($itemId);
            if(!empty($res['rows'][0]['_main_sku'])){
                $mainSku = $res['rows'][0]['_main_sku'] . '001';
            }
        } elseif ($type == 'wish') {
            $res = serv_rapi_publish::getWishItemInfo($itemId);
            if(!empty($res['rows'][0]['main_sku'])){
                preg_match('/>([A-Z]+[0-9]+) </', $res['rows'][0]['main_sku'], $mainSku);
                $mainSku = !empty($mainSku[1]) ? trim($mainSku[1]) : '';
            }
        } elseif ($type == 'shopee') {
            $ai = explode("/", $itemId);
            $shopId = $ai[0];
            $acc = L::sql("SELECT
                shopId, account 
            FROM
                shopee_account 
            WHERE
                shopId = '{$shopId}'");
            $account = $acc[0]['account'];
            $id = $ai[1];
            $res = serv_rapi_publish::getShopeeItemInfo($account,$id);
            if(!empty($res['rows'][0]['item_sku'])){
                preg_match('/<li>([A-Z0-9_+= -]+)/', $res['rows'][0]['item_sku'], $mainSku);
                $mainSku = !empty($mainSku[1]) ? trim($mainSku[1]) : '';
            }
        }
        if(!empty($mainSku)){
            $skuInfo = self::getPdmSkuInfo($mainSku);
            return ['url' => $skuInfo['purchaseUrl'], 'sku' => $mainSku, 'data' => $skuInfo];
//            $res = serv_rapi_publish::getSku($mainSku);
//            if(!empty($res['rows'][0]['sku'])){
//                $info = $res['rows'][0];
//                $id = $info['goods_id'];
//                $itemId = $info['id'];
//                $data = serv_rapi_publish::getSkuDetail($id,$itemId);
//                $data['scalageWeight'] = $info['scalage_weight'];   //质检重量
//                $data['avgWeight'] = $info['avg_weight'];   //包装平均重量
//                $data['volumeWeight'] = $info['volume_weight'];   //体积重量
//                return ['url' => $data['purchaseUrl'], 'sku' => $mainSku, 'data' => $data];
//            }
        }
        return null;
    }

    /**
     * 描述 : 获取采购链接
     * 作者 : Zoro.Zhu
     */
    public static function getPurchaseUrl($url){
        if(strstr($url, '.wish.')){
            $type = 'wish';
            $itemId = substr(trim($url),-24);
        }else if(strstr($url, 'shopee.')){
            $type = 'shopee';
            $itemId = substr($url,-20);
            $itemId = trim($itemId, '/');
        }else {
            $type = 'ebay';
            preg_match('/\/([\d][\d][\d][\d]+)/', $url, $itemId);
            $itemId = !empty($itemId[0]) ? trim($itemId[0], '/') : '';
        }
        //先查数据库
        if(!empty($itemId)){
            $sql = "SELECT
                itemId, purchaseUrl,sku,`data`
            FROM
                `purchase_url` 
            WHERE
                itemId = '{$itemId}'";
            $info = L::sql($sql);
            if (!empty($info[0]['purchaseUrl'])) {
                $data['url'] = json_decode($info[0]['purchaseUrl'], true);
                $data['sku'] = $info[0]['sku'];
                $data['data'] = json_decode($info[0]['data'], true);
                return $data;
            } else {
                $res = self::manuUrl($itemId, $type);
                if($res === null){
                    return [];
                }
                $insertUrl = addslashes($url);
                $purchaseUrl = addslashes(json_encode($res['url']));
                $json = addslashes(json_encode($res['data']));
                $sql = "INSERT INTO `purchase_url`(
                  `itemId`, `url`, `sku`, `purchaseUrl`, `addTime`, `data`
                ) VALUES (
                  '{$itemId}', '{$insertUrl}', '{$res['sku']}', '{$purchaseUrl}', '" . date('Y-m-d H:i:s') . "', '{$json}'
                )";
                L::sql($sql);
                return $res;
            }
        }
        return [];
    }

    public function test(){
        $res = self::getPurchaseUrl('https://shopee.sg/product/108055106/5264087811');
        p($res);
    }

    /**
     * 描述 : 根据标题获取采购链接
     * 作者 : Zoro.Zhu
     */
    public static function titleToUrl($title = ''){
        set_time_limit(0);
        session_commit();
        $title = !empty($title) ? $title : $_GET['title'];
//        $title = "Drawer Door Shell Cup Pull Knob Cabinet Wardrobe Kitchen Cupboard Handle 24 Pack";
        $res = serv_rapi_publish::search(['type' => 1, 'title' => $title, 'size' => 1]);
        if(!empty($res['data'][0]['mainSku'])){
            $sql = "SELECT
                itemId, purchaseUrl,sku
            FROM
                `purchase_url` 
            WHERE
                sku like '{$res['data'][0]['mainSku']}%'";
            $info = L::sql($sql);
            if (!empty($info[0]['purchaseUrl'])) {
                $res = json_decode($info[0]['purchaseUrl'], true);
                $res[] = 'https://6beams.com/?c=ctrl_wish_purchaseUrl&a=index&sku=' . $info[0]['sku'];
                echo '<div id="url">';
                echo json_encode($res);
                echo '</div>';
                echo '<div id="oldUrl">';
                echo $_REQUEST['oldUrl'];
                echo '</div>';
            } else {
                $mainSku = $res['data'][0]['mainSku'];
                $res = serv_rapi_publish::getSku($mainSku);
                if(!empty($res['rows'][0]['sku'])){
                    $info = $res['rows'][0];
                    $id = $info['goods_id'];
                    $itemId = $info['id'];
                    $data = serv_rapi_publish::getSkuDetail($id,$itemId);
                    $data['scalageWeight'] = $info['scalage_weight'];   //质检重量
                    $data['avgWeight'] = $info['avg_weight'];   //包装平均重量
                    $data['volumeWeight'] = $info['volume_weight'];   //体积重量
                    $res = ['url' => $data['purchaseUrl'], 'sku' => $mainSku, 'data' => $data];
                    $insertUrl = addslashes($title);
                    $purchaseUrl = addslashes(json_encode($res['url']));
                    $json = addslashes(json_encode($res['data']));
                    $sql = "INSERT INTO `purchase_url`(
                      `itemId`, `url`, `sku`, `purchaseUrl`, `addTime`, `data`
                    ) VALUES (
                      '" . md5($insertUrl) . "', '{$insertUrl}', '{$res['sku']}', '{$purchaseUrl}', '" . date('Y-m-d H:i:s') . "', '{$json}'
                    )";
                    L::sql($sql);
                    $res['url'][] = 'https://6beams.com/?c=ctrl_wish_purchaseUrl&a=index&sku=' . $res['sku'];
                    echo '<div id="url">';
                    echo json_encode($res['url']);
                    echo '</div>';
                    echo '<div id="oldUrl">';
                    echo $_REQUEST['oldUrl'];
                    echo '</div>';
                }
            }
        } else {
            echo '匹配失败';
            echo '<script language="javascript">
            self.close();
            </script>';
        }
    }

    public function test2(){
        set_time_limit(0);
        $res = [
            'UUU105270',
            'UUU212538',
            'PPP229728'
        ];
        foreach($res as $row) {
            $res = serv_rapi_publish::getSku($row);
            if(!empty($res['rows'][0]['sku'])){
                $info = $res['rows'][0];
                $id = $info['goods_id'];
                $itemId = $info['id'];
                $data = serv_rapi_publish::getSkuDetail($id,$itemId);
                $data['scalageWeight'] = $info['scalage_weight'];   //质检重量
                $data['avgWeight'] = $info['avg_weight'];   //包装平均重量
                $data['volumeWeight'] = $info['volume_weight'];   //体积重量
                $json = addslashes(json_encode($data));
                L::sql("UPDATE `purchase_url` SET `data` = '{$json}' WHERE `sku` = '{$row}'");
            }
        }
    }

    /**
     * 描述 : 获取购买链接
     * 作者 : Zoro.Zhu
     */
    public function getManuUrl(){
        if($_REQUEST['url'] == 'undefined'){
            return null;
        }
        $url = $_REQUEST['url'];
        preg_match('/\/([\d][\d][\d][\d]+)/', $url, $itemId);
        $site = [];
        if(strstr($url, '//www.ebay.com/')){
            $site[] = 'US';
            $site[] = 'eBayMotors';
        } else if(strstr($url, '//www.ebay.co.uk/')){
            $site[] = 'UK';
        } else if(strstr($url, '//www.ebay.ca/')){
            $site[] = 'Canada';
        }
        $search = array(
            'platformId' => 1,
            'itemId' => [trim($itemId[0],'/')],
            'type' => 1,
//            'siteCode' => $site,
            'size' => 10,
            'page' => 1,
        );
//        !empty($site) && $search['siteCode'] = $site;
        $res = serv_rapi_publish::search($search);
        if(!empty($res['data']['0']['mainSku'])){
            $mainSku = $res['data']['0']['mainSku'];
            $purchaseUrl = L::sql("SELECT 
                link_url 
            FROM 
                `goods_sku_manufacture_mapper_audit` 
            WHERE 
                main_sku = '{$mainSku}'", 'product');
            $purchaseUrl2 = L::sql("SELECT
                spare_product_url 
            FROM
                `goods` 
            WHERE
                main_sku =  '{$mainSku}'", 'product');
            !empty($purchaseUrl[0]['link_url']) && $productUrl[] = $purchaseUrl[0]['link_url'];
            !empty($purchaseUrl2[0]['spare_product_url']) && $productUrl[] = $purchaseUrl2[0]['spare_product_url'];
            if(!empty($productUrl)){
                echo '<div id="url">';
                echo json_encode($productUrl);
                echo '</div>';
                echo '<div id="oldUrl">';
                echo $_REQUEST['oldUrl'];
                echo '</div>';
            }
        }
    }

    /**
     * 描述 : 通过店小秘爬取数据
     * 作者 : Zoro.Zhu
     */
    public function getDxmItem(){
        set_time_limit(0);
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            account = 'zorozhu' ");
        $cookie = $account[0]['cookie'];
        $url = [
            'https://www.wish.com/product/58eca4ec4e5e93191214746d',
        ];
        foreach ($url as $a){
            serv_rep_dxm::getItemInfo($cookie, $a);
        }
    }

    /**
     * 描述 : 获取SKU的基础资料
     * 作者 : Zoro.Zhu
     */
    public static function getPdmSkuInfo($sku){
        $data = serv_rapi_publish::getPdmSkuInfo($sku);     //获取SKU信息
        $info['nameCn'] = $data['nameCn'];
        $info['nameEn'] = $data['nameEn'];
        $info['avgWeight'] = $data['packagingWeight'];
        $info['volumeWeight'] = $data['chargedWeight'];
        $info['scalageWeight'] = $data['weight'];
        $logisAttr = model_com::getLogisAttr();
        $spuInfo = serv_rapi_publish::getPdmSpuInfo($sku);     //获取SKU信息
        $info['productAttr'] = isset($logisAttr[$spuInfo['logisticsAttr']]) ? $logisAttr[$spuInfo['logisticsAttr']] : $spuInfo['logisticsAttr'];
        $info['spu'] = $spuInfo['skuId'];
        $info['skuAttr'] = serv_rapi_publish::getPdmSpuAttrInfo($info['spu']);     //获取SPU属性信息
        $info['seller'] = serv_rapi_publish::getPdmSellerInfo($sku);     //获取供应商信息
        $info['purchaseUrl'] = array_column($info['seller'], 'sellerUrl');
        return $info;
    }

    /**
     * 描述 : 采集shopee数据
     * 作者 : Zoro.Zhu
     */
    public function getShopeeDxm(){
//        core_base::log($_GET,'getShopeeDxm');
        set_time_limit(0);
        $dxmAccount = !empty($_GET['dxmAccount']) ? trim($_GET['dxmAccount']) : 'zorozhu';
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            account = '{$dxmAccount}' ");
        $cookie = $account[0]['cookie'];
        $shopId = trim($_GET['shopId']);
        $account = trim($_GET['account']);
        $accountName = trim($_GET['accountName']);
        $siteAy = explode('-', $accountName);
        $url = "https://shopee.sg/product/";
        foreach ($siteAy as $s){
            $s == 'PH' && $url = "https://shopee.ph/product/";
            $s == 'MY' && $url = "https://shopee.com.my/product/";
        }
        L::sql("INSERT INTO `shopee_account`(
          `shopId`, `account`
        ) VALUES (
          '{$shopId}', '{$account}'
        ) ON DUPLICATE KEY UPDATE 
         `account` = VALUES(`account`)");
        $itemId = explode(",", trim($_GET['itemId'], ','));
        foreach ($itemId as $i) {
            $urls = "{$url}{$shopId}/{$i}";
            serv_rep_dxm::getItemInfo($cookie, $urls);
        }
        echo '已采集，请关闭';
        echo '<script language="javascript">
        function clock(){i=i-1
        document.title="本窗口将在"+i+"秒后自动闭!";
        if(i>0)setTimeout("clock();",1000);
        else self.close();}
        var i=2;
        clock();
        </script>';
    }

    public function addProduct(){
        $url = "https://www.wish.com/api/user/wishlist/add-product";
        $post = [
            'product_ids[]' => '5fa39a2994554cdba3628821',
            'securedtouch_token' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiYVkwVDRpLzN1MFUzcVZiMkllZVJDVEtuN0hrOGdjeHJlbEFheUdTRTB4djl0STN6MnVkaUpaWlFKT3ZyNjJ5cG5KdCtrb1VzTHF4WWk1bng0b1liRW5sbDc2UDkyY3BmcnVVb3NhZmcxZnoyWW1NeVhQdTJiMnpDdkZOdmN3MnNTVHBDVXVKT21vaVNyNllXQ1YvZFF4TC9tVHpZSXRCMzR6UFpnRUJtWTlOZjZ1aHFwcE9lcDJWdjViNjVUTHk3NzQyL2JzMUxhQUNTVG84UTg2U0lYNDlPczFMTVk1V0owWW8xdzgybFQ5NXJLQzd1TXI4YytzZk5GTjZtckhyVWtMN1VyL1d6NWlOeVdmUnNzTXpwYVp0VDlnYk1LQlZTdkNVdmZ2dkEycitkT0M4YXlKRER5cUx5b05HcUp3SVpveDM5MmQ5S3FMMldOWlp5cksyOFNHWW1ob2FlNkJBU3JJUVhTTXp0T1I4PSIsImlhdCI6MTYwNDg5MjU5MywiZXhwIjoxNjA1NDk3MzkzfQ.JiRW-vj4PLFbi3jPVa_hJaB7wxBRzR0UrbxInJvnjgQ',
        ];
        $header = [
            'cookie:__zlcmid=zojNY4Eu9lpv8I; visitor_id=21b75aff2a824464803e480a0c947e0b; _ga=GA1.2.302520635.1599549529; __ssid=1670d72a8e7c589131fd0a0c12e4c58; __stripe_mid=5b22dde7-18d0-42d1-95cc-43f296977ae21667c0; __utma=96128154.302520635.1599549529.1603109050.1603113438.2; __utmz=96128154.1603113438.2.2.utmcsr=merchant.wish.com|utmccn=(referral)|utmcmd=referral|utmcct=/product; _fbp=fb.1.1603790144818.2023014345; _pin_unauth=dWlkPU56RmhOak14TVdZdE1qbGxOQzAwT0dOakxUbGhOak10TVRjek1ESTNOekkyTVdZMw; G_ENABLED_IDPS=google; authentication_id=781d80018508819521b6264f12d64a1c; _xsrf=2|216fc438|9f970c6e2e4eaeb234137c74dbcf9b41|1603792436; vendor_user_tracker=d6ca4f101e5abdabc2cc7a20493e59e286d09b5f0c27303e7d79a00a94f634b2; bsid=a3a406d3746704726ab41e3fda08d6ee; _is_desktop=true; _timezone=8; sweeper_session="2|1:0|10:1604892591|15:sweeper_session|84:NjE2M2YwYWUtODQ1Yi00ODM4LWE2OGEtMDc4OWQyMjYzZDViMjAyMC0xMC0yNyAwOToxNTo0Ny43MDYzMDQ=|6d50ff05ea854eb8e653a2250d610358c2bd6c4b30ada4cac20cc4be34d9316d"; sessionRefreshed_5ecb71c93fb69d0673c0c1d0=true; __stripe_sid=5c7823a5-44d2-4754-a2d4-6ab6dcb11939eb5609; sweeper_uuid=bd2b79afe0df49818fe99c0da743f110',
            'x-xsrftoken:2|216fc438|9f970c6e2e4eaeb234137c74dbcf9b41|1603792436',
        ];
        $res = of_base_com_net::request($url, ['post' => $post, 'header' => $header]);
        p($res);
    }

    public static function insert(){
        set_time_limit(0);
        $account = L::sql("SELECT
            account, cookie 
        FROM
            vs_account_cookie 
        WHERE
            account = 'zorozhu' ");
        $cookie = $account[0]['cookie'];
        $urls = [
            'https://www.wish.com/product/58b8c6659602e05277fa6100',
        ];
        foreach ($urls as $url) {
            serv_rep_dxm::getItemInfo($cookie, $url);
        }
    }

    /**
     * 描述 : 下载PDM的产品信息
     * 作者 : Zoro.Zhu
     */
    public static function getPdmInfo($spu){
        //查询标题，描述，标签
        $spuInfo = model_product::getPdmInfo($spu);
        $data = [];
        //标题
        $data['title'] = $spuInfo['title']['en'];
        $title = serv_rapi_product::getTitle(['main_sku' => $spu, 'platformId' => 1,4, 'languageId' => 2, 'isAuto' => false]);
        if($title !== false && !empty($title['list'])){
            //多个取其中一个就好了，随机取一个
            $rand = array_rand($title['list'], 1);
            $data['title'] = $title['list'][$rand]['title'];
        }
        $data['title'] = str_replace('\\', "", $data['title']);
        //描述
        $data['describe'] = model_com::html2text($spuInfo['describe']['en']);
        $data['describe'] = str_replace("\n\n\n\n\n", "\n\n\n\n", $data['describe']);
        $data['describe'] = str_replace("\n\n\n\n", "\n\n\n", $data['describe']);
        $data['describe'] = str_replace("\n\n\n", "\n\n", $data['describe']);
        $data['describe'] = str_replace("\n\n", "\n", $data['describe']);
        //标签
        $label = explode(' ', $data['title']);
        $data['label'] = '';
        foreach($label as $k => $v) {
            $k < 10 && $data['label'] .= $v . ',';
        }
        $data['label'] = trim($data['label'], ',');     //初步生成标签
        $keyword = serv_rapi_product::getKeyword(['main_sku' => $spu, 'platformId' => 1,4, 'languageId' => 2]);
        if($keyword !== false && !empty($keyword['list'])){
            $data['label'] = '';
            foreach($keyword['list'] as $k => $v) {
                $k < 10 && $data['label'] .= $v['keyword'] . ',';
            }
            $data['label'] = trim($data['label'], ',');     //初步生成标签
        }
        $data['supplierLink'] = !empty($spuInfo['supplierLink']) ? join("\n", $spuInfo['supplierLink']): '';       //采购链接
        $data['skuList'] = array_keys($spuInfo['skuPack']);     //sku列表
        $skuData = [];
        $sellerAy = [];
        foreach($data['skuList'] as $key => $sku){
            $skuData[$sku]['sku'] = $sku;
            $skuInfo = model_product::getPdmInfo($sku);
            $price = model_product::getPdmInfo($sku, 'base.EB.US', ['price']);
            if(empty($price['price']['price'])){
                continue;
            }
            $priceRmb = round($price['price']['price'] / 100 * 6.88, 2);  //本地价格
            //为了防止不同批次下载，价格相同，做一下随机变更价格
            $num = rand(90,105);
            $skuData[$sku]['price'] = $price['price']['price'] * $num / 10000;  //价格($)
            $skuData[$sku]['priceRmb'] = $priceRmb;       //本地价格
            $skuData[$sku]['skuAttr'] = $skuInfo['skuAttr'];
            //变种图
            $img = model_product::getImg($sku);
            $skuData[$sku]['img'] = !empty($img[0]['path']) ? $img[0]['url'] . '/' . $img[0]['path'] : '';
            $seller = model_product::getSeller($sku);
            foreach($seller as $a){
                $sellerAy[$a['seller']] = $a['skuUrl'];
            }
        }
        $data['supplierLink'] = !empty($sellerAy) ? join("\n", $sellerAy): '';       //采购链接
        $data['skuData'] = $skuData;
        $imgAll = model_product::getImg($spu);      //图片为空，错误
        if(empty($imgAll)){
            return false;
        }
        //主图
        $data['mainImg'] = $imgAll[0]['url'] . '/' . $imgAll[0]['path'];
        unset($imgAll[0]);
        $other = [];
        if(!empty($imgAll)){
            foreach($imgAll as $row){
                $other[] = $row['url'] . '/' . $row['path'];
            }
        }
        $data['otherImg'] = $other;
        return $data;
    }

    /**
     * 描述 : 下载表格
     * 作者 : Zoro.Zhu
     */
    public function downloadProduct(){
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $spuGet = trim($_GET['spu']);
        $spuGet = explode(',', $spuGet);
        $fileName = isset($_GET['fileName']) ? trim($_GET['fileName']) : '';
        $firstLine = [
            'spu' => 'ParentSKU',
            'sku' => 'SKU',
            'title' => '产品名称',
            'describe' => '产品描述',
            'label' => '产品标签',
            'brand' => '品牌',
            'upc' => 'UPC',
            'landingUrl' => 'landingPageUrl',
            'msrp' => 'msrp',
            'colour' => '颜色',
            'size' => '尺寸值',
            'sellerUrl' => '来源url',
            'price' => '价格($)',
            'priceRmb' => '本地价格',
            'fee' => '运费($)',
            'feeRmb' => '运费(CNY)',
            'stock' => '库存量',
            'mainImg' => '主图（URL）地址',
            'skuImg' => '变种图（URL）地址',
            'otherImg1' => '附图1（URL）地址',
            'otherImg2' => '附图2（URL）地址',
            'otherImg3' => '附图3（URL）地址',
            'otherImg4' => '附图4（URL）地址',
            'otherImg5' => '附图5（URL）地址',
            'otherImg6' => '附图6（URL）地址',
            'otherImg7' => '附图7（URL）地址',
            'otherImg8' => '附图8（URL）地址',
            'otherImg9' => '附图9（URL）地址',
            'otherImg10' => '附图10（URL）地址',
            'otherImg11' => '附图11（URL）地址',
            'otherImg12' => '附图12（URL）地址',
            'otherImg13' => '附图13（URL）地址',
            'otherImg14' => '附图14（URL）地址',
            'otherImg15' => '附图15（URL）地址',
            'otherImg16' => '附图16（URL）地址',
            'otherImg17' => '附图17（URL）地址',
            'otherImg18' => '附图18（URL）地址',
            'otherImg19' => '附图19（URL）地址',
            'otherImg20' => '附图20（URL）地址',
        ];
        $data = [];
        foreach ($spuGet as $spu){
            $spu = trim($spu);
            if(empty($spu)){
                continue;
            }
            $spuInfo = self::getPdmInfo($spu);
            if(!empty($spuInfo) && !empty($spuInfo['skuData'])){
                foreach($spuInfo['skuData'] as $sku => $info){
                    $skuAttr = !empty($info['skuAttr']) ? join(' ', $info['skuAttr']) : '';
                    $data[] = [
                        'spu' => $spu,
                        'sku' => $spu . '-' . $skuAttr,
                        'title' => $spuInfo['title'],
                        'describe' => $spuInfo['describe'],
                        'label' => $spuInfo['label'],
                        'brand' => '',
                        'upc' => '',
                        'landingUrl' => '',
                        'msrp' => round($info['price'] * 1.8, 2),
                        'colour' => '',
                        'size' => $skuAttr,
                        'sellerUrl' => $spuInfo['supplierLink'],
                        'price' => round($info['price'] * 0.9, 2),
                        'priceRmb' => round($info['priceRmb'] * 0.9, 2),
                        'fee' => round($info['price'] * 0.1, 2),
                        'feeRmb' => round($info['priceRmb'] * 0.1, 2),
                        'stock' => 100,
                        'mainImg' => $spuInfo['mainImg'],
                        'skuImg' => $info['img'],
                        'otherImg1' => !empty($spuInfo['otherImg'][0]) ? $spuInfo['otherImg'][0] : '',
                        'otherImg2' => !empty($spuInfo['otherImg'][1]) ? $spuInfo['otherImg'][1] : '',
                        'otherImg3' => !empty($spuInfo['otherImg'][2]) ? $spuInfo['otherImg'][2] : '',
                        'otherImg4' => !empty($spuInfo['otherImg'][3]) ? $spuInfo['otherImg'][3] : '',
                        'otherImg5' => !empty($spuInfo['otherImg'][4]) ? $spuInfo['otherImg'][4] : '',
                        'otherImg6' => !empty($spuInfo['otherImg'][5]) ? $spuInfo['otherImg'][5] : '',
                        'otherImg7' => !empty($spuInfo['otherImg'][6]) ? $spuInfo['otherImg'][6] : '',
                        'otherImg8' => !empty($spuInfo['otherImg'][7]) ? $spuInfo['otherImg'][7] : '',
                        'otherImg9' => !empty($spuInfo['otherImg'][8]) ? $spuInfo['otherImg'][8] : '',
                        'otherImg10' => !empty($spuInfo['otherImg'][9]) ? $spuInfo['otherImg'][9] : '',
                        'otherImg11' => !empty($spuInfo['otherImg'][10]) ? $spuInfo['otherImg'][10] : '',
                        'otherImg12' => !empty($spuInfo['otherImg'][11]) ? $spuInfo['otherImg'][11] : '',
                        'otherImg13' => !empty($spuInfo['otherImg'][12]) ? $spuInfo['otherImg'][12] : '',
                        'otherImg14' => !empty($spuInfo['otherImg'][13]) ? $spuInfo['otherImg'][13] : '',
                        'otherImg15' => !empty($spuInfo['otherImg'][14]) ? $spuInfo['otherImg'][14] : '',
                        'otherImg16' => !empty($spuInfo['otherImg'][15]) ? $spuInfo['otherImg'][15] : '',
                        'otherImg17' => !empty($spuInfo['otherImg'][16]) ? $spuInfo['otherImg'][16] : '',
                        'otherImg18' => !empty($spuInfo['otherImg'][17]) ? $spuInfo['otherImg'][17] : '',
                        'otherImg19' => !empty($spuInfo['otherImg'][18]) ? $spuInfo['otherImg'][18] : '',
                        'otherImg20' => '',
                    ];
                }
            }
        }
        if(!empty($data)){
            $fileName = (!empty($fileName) ? $fileName : $spu) . '-店小秘WISH.xls';
            model_com::xlsDownload($firstLine,$data,$fileName);
        }
    }

    /**
     * 描述 : 下载wish产品的数据
     * 作者 : Zoro.Zhu
     */
    public static function sortOutWishProduct($itemId = ''){
        $token = model_wishBuyAccount::getParamsInfo(['account' => '14194296@qq.com']);
        $params = $token[0] + ['productId' => $itemId];
        //先浏览产品,并获取变种ID
        $variation = serv_rep_wish::getProductInfoNew($params);
        $data = [];
        if(!empty($variation)){
            $spu = of_base_com_str::uniqid('Z',3);
            $imgUrl = !empty($variation['extraPhotoUrls']) ? $variation['extraPhotoUrls'] : [];
            if(!empty($imgUrl)){
                foreach ($imgUrl as &$img){
                    $img = str_replace("small", "large", $img);
                }
            }
            foreach($variation['commerceProductInfo']['variations'] as $var){
                //sequence_id
                $skuAttr = '';
                !empty($var['size']) && $skuAttr .= "_{$var['size']}";
                !empty($var['color']) && $skuAttr .= "_{$var['color']}";
                $data[] = [
                    'spu' => $spu,
                    'sku' => $spu .  $skuAttr,
                    'title' => $variation['name'],
                    'describe' => @iconv('UTF-8', 'UTF-8//IGNORE', $variation['description']),
                    'label' => join(',', $variation['keywords']),
                    'brand' => '',
                    'upc' => '',
                    'landingUrl' => '',
                    'msrp' => round($var['price'] * 2, 2),
                    'colour' => $var['color'],
                    'size' => $var['size'],
                    'sellerUrl' => "https://www.wish.com/product/{$itemId}?share=web",
                    'price' => round($var['price'] * 0.98, 2),
                    'priceRmb' => round($var['price'] * 6.4, 2),
                    'fee' => round($var['localized_shipping']['localized_value'], 2),
                    'feeRmb' => round($var['localized_shipping']['localized_value'] * 6.4, 2),
                    'stock' => 100,
                    'mainImg' => $variation['productPagePicture'],
                    'skuImg' => !empty($imgUrl[$var['sequence_id']]) ? $imgUrl[$var['sequence_id']] : '',
                    'otherImg1' => !empty($imgUrl[0]) ? $imgUrl[0] : '',
                    'otherImg2' => !empty($imgUrl[1]) ? $imgUrl[1] : '',
                    'otherImg3' => !empty($imgUrl[2]) ? $imgUrl[2] : '',
                    'otherImg4' => !empty($imgUrl[3]) ? $imgUrl[3] : '',
                    'otherImg5' => !empty($imgUrl[4]) ? $imgUrl[4] : '',
                    'otherImg6' => !empty($imgUrl[5]) ? $imgUrl[5] : '',
                    'otherImg7' => !empty($imgUrl[6]) ? $imgUrl[6] : '',
                    'otherImg8' => !empty($imgUrl[7]) ? $imgUrl[7] : '',
                    'otherImg9' => !empty($imgUrl[8]) ? $imgUrl[8] : '',
                    'otherImg10' => !empty($imgUrl[9]) ? $imgUrl[9] : '',
                    'otherImg11' => !empty($imgUrl[10]) ? $imgUrl[10] : '',
                    'otherImg12' => !empty($imgUrl[11]) ? $imgUrl[11] : '',
                    'otherImg13' => !empty($imgUrl[12]) ? $imgUrl[12] : '',
                    'otherImg14' => !empty($imgUrl[13]) ? $imgUrl[13] : '',
                    'otherImg15' => !empty($imgUrl[14]) ? $imgUrl[14] : '',
                    'otherImg16' => !empty($imgUrl[15]) ? $imgUrl[15] : '',
                    'otherImg17' => !empty($imgUrl[16]) ? $imgUrl[16] : '',
                    'otherImg18' => !empty($imgUrl[17]) ? $imgUrl[17] : '',
                    'otherImg19' => !empty($imgUrl[18]) ? $imgUrl[18] : '',
                    'otherImg20' => '',
                ];
            }
        }
        return $data;
    }

    /**
     * 描述 : 下载wish产品数据
     * 作者 : Zoro.Zhu
     */
    public static function downloadWishProduct(){
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $itemIds = explode(",", $_GET['productId']);
        $data = [];
        foreach($itemIds as $itemId){
            $da = self::sortOutWishProduct(trim($itemId));
            $data = array_merge($data, $da);
        }
        $firstLine = [
            'spu' => 'ParentSKU',
            'sku' => 'SKU',
            'title' => '产品名称',
            'describe' => '产品描述',
            'label' => '产品标签',
            'brand' => '品牌',
            'upc' => 'UPC',
            'landingUrl' => 'landingPageUrl',
            'msrp' => 'msrp',
            'colour' => '颜色',
            'size' => '尺寸值',
            'sellerUrl' => '来源url',
            'price' => '价格($)',
            'priceRmb' => '本地价格',
            'fee' => '运费($)',
            'feeRmb' => '运费(CNY)',
            'stock' => '库存量',
            'mainImg' => '主图（URL）地址',
            'skuImg' => '变种图（URL）地址',
            'otherImg1' => '附图1（URL）地址',
            'otherImg2' => '附图2（URL）地址',
            'otherImg3' => '附图3（URL）地址',
            'otherImg4' => '附图4（URL）地址',
            'otherImg5' => '附图5（URL）地址',
            'otherImg6' => '附图6（URL）地址',
            'otherImg7' => '附图7（URL）地址',
            'otherImg8' => '附图8（URL）地址',
            'otherImg9' => '附图9（URL）地址',
            'otherImg10' => '附图10（URL）地址',
            'otherImg11' => '附图11（URL）地址',
            'otherImg12' => '附图12（URL）地址',
            'otherImg13' => '附图13（URL）地址',
            'otherImg14' => '附图14（URL）地址',
            'otherImg15' => '附图15（URL）地址',
            'otherImg16' => '附图16（URL）地址',
            'otherImg17' => '附图17（URL）地址',
            'otherImg18' => '附图18（URL）地址',
            'otherImg19' => '附图19（URL）地址',
            'otherImg20' => '附图20（URL）地址',
        ];
        $fileName = date('H:i:s Y-m-d') . '-店小秘WISH.xls';
        model_com::xlsDownload($firstLine,$data,$fileName);
    }

    /**
     * 描述 : wish产品数据下载
     * 作者 : Zoro.Zhu
     */
    public function wishProductDownload(){
        $this->view->headTitle = 'wish产品数据下载';
        $this->display('/html/wish/wishProductDownload.html');
    }

}

return true;
